<template>
  <div class="app-container">
    <!--工具栏-->
    <div class="head-container">
      <div v-if="crud.props.searchToggle">
        <!-- 搜索 --><label class="el-form-item-label">入学年份</label>
        <el-select
          v-model="query.enterDate"
          size="small"
          class="filter-item"
          style="width: 90px"
          remote
          :remote-method="getEnterYears()"
          @change="loadQueryColleges"
        >
          <el-option v-for="item in years" :key="item" :label="item" :value="item" />
        </el-select>
        <el-select
          v-model="query.academyDepartId"
          clearable
          size="small"
          filterable
          placeholder="请选择院系"
          class="filter-item"
          style="width: 190px"
          @change="loadQueryMajors"
        >
          <el-option
            v-for="item in queryColleges"
            :key="item.id"
            :label="item.name"
            :value="item.id"
          />
        </el-select>
        <el-select
          v-model="query.majorDepartId"
          clearable
          size="small"
          filterable
          placeholder="请选择专业"
          class="filter-item"
          style="width: 150px"
          @change="crud.toQuery"
        >
          <el-option
            v-for="item in queryMajors"
            :key="item.id"
            :label="item.name"
            :value="item.id"
          />
        </el-select>
        <el-input v-model="query.name" clearable placeholder="输入姓名搜索" style="width: 130px;" class="filter-item" @keyup.enter.native="crud.toQuery" />
        <el-select
          v-model="query.nationId"
          filterable
          clearable
          size="small"
          placeholder="民族"
          class="filter-item"
          style="width: 120px"
          @change="crud.toQuery"
        >
          <el-option
            v-for="item in dict.nation"
            :key="item.id"
            :label="item.label"
            :value="item.value"
          />
        </el-select>
        <el-select
          v-model="query.educationalLevelId"
          clearable
          size="small"
          placeholder="学历层次"
          class="filter-item"
          style="width: 120px"
          @change="crud.toQuery"
        >
          <el-option
            v-for="item in dict.education"
            :key="item.id"
            :label="item.label"
            :value="item.value"
          />
        </el-select>
        <el-select
          v-model="query.verifyStatus"
          clearable
          size="small"
          placeholder="认证状态"
          class="filter-item"
          style="width: 115px"
          @change="crud.toQuery"
        >
          <el-option
            v-for="item in dict.verify_status"
            :key="item.id"
            :label="item.label"
            :value="item.value"
          />
        </el-select>
        <rrOperation :crud="crud" />
      </div>
      <!--如果想在工具栏加入更多按钮，可以使用插槽方式， slot = 'left' or 'right'-->
      <!--modify by yaowenya;2021.03.15;begin;-->
      <crudOperation :permission="permission">
        <template slot="right">
          <iframe name="targetifr" style="display:none" />
          <el-upload
            class="filter-item"
            :headers="headers"
            :action="studentBatchImportApi"
            :on-preview="handlePreview"
            :on-remove="handleRemove"
            multiple
            :limit="1"
            :on-exceed="handleExceed"
            :file-list="fileList"
            :before-upload="beforeUploadFile"
            :on-error="handleUploadError"
            :on-success="handleUploadSuccess"
            :on-progress="handleUploadProcess"
            accept=".xls, .xlsx"
          >
            <el-button size="mini" type="primary" icon="el-icon-upload2">导入</el-button>
          </el-upload>
        </template>
      </crudOperation>
      <!--modify by yaowenya;2021.03.15;end;-->
      <!--表单组件-->
      <el-dialog :close-on-click-modal="false" :before-close="crud.cancelCU" :visible.sync="crud.status.cu > 0" :title="crud.status.title" width="800px">
        <el-form ref="form" inline :model="form" :rules="rules" size="small" label-width="80px">
          <el-tabs v-model="activeName" type="card">
            <el-tab-pane label="基础信息" name="first">
              <el-row :gutter="0.5">
                <el-col :span="12">
                  <el-form-item label="姓名" prop="name">
                    <el-input v-model="form.name" class="input" />
                  </el-form-item>
                </el-col>
                <el-col :span="12">
                  <el-form-item label="性别" prop="gender">
                    <el-radio v-for="item in dict.gender_type" :key="item.id" v-model="form.gender" :label="item.value">{{
                      item.label }}
                    </el-radio>
                  </el-form-item>
                </el-col>
              </el-row>
              <el-row :gutter="0.5">
                <el-col :span="12">
                  <el-form-item label="身份证号" prop="idCardNo">
                    <el-input v-model="form.idCardNo" class="input" />
                  </el-form-item>
                </el-col>
                <el-col :span="12">
                  <el-form-item label="出生年月" prop="birthDate">
                    <el-date-picker v-model="form.birthDate" type="month" format="yyyy-MM" style="width: 250px;" />
                  </el-form-item>
                </el-col>
              </el-row>
              <el-row :gutter="0.5">
                <el-col :span="12">
                  <el-form-item label="民族" prop="nationId">
                    <el-select v-model="form.nationId" filterable placeholder="请选择" class="input">
                      <el-option
                        v-for="item in dict.nation"
                        :key="item.id"
                        :label="item.label"
                        :value="item.value"
                      />
                    </el-select>
                  </el-form-item>
                </el-col>
                <el-col :span="12">
                  <el-form-item label="政治面貌" prop="politicalId">
                    <el-select v-model="form.politicalId" filterable placeholder="请选择" class="input">
                      <el-option
                        v-for="item in dict.political_climate"
                        :key="item.id"
                        :label="item.label"
                        :value="item.value"
                      />
                    </el-select>
                  </el-form-item>
                </el-col>
              </el-row>

              <el-row :gutter="0.5">
                <el-col :span="8">
                  <el-form-item label="联系电话" prop="phone">
                    <el-input v-model="form.phone" style="width: 160px;" />
                  </el-form-item>
                </el-col>
                <el-col :span="8">
                  <el-form-item label="微信号">
                    <el-input v-model="form.weixin" style="width: 160px;" />
                  </el-form-item>
                </el-col>
                <el-col :span="8">
                  <el-form-item label="QQ号">
                    <el-input v-model="form.qq" style="width: 160px;" />
                  </el-form-item>
                </el-col>
              </el-row>
              <el-row :gutter="0.5">
                <el-col :span="24">
                  <el-form-item label="当前地址">
                    <el-input v-model="form.address" style="width: 670px;" />
                  </el-form-item>
                </el-col>
              </el-row>
            </el-tab-pane>

            <el-tab-pane label="学习经历" name="second">
              <el-row>
                <el-col :span="24">
                  <el-form-item label="生源地">
                    <el-input v-model="form.birthPlace" style="width: 600px;" />
                  </el-form-item>
                </el-col>
              </el-row>
              <el-row :gutter="0.5">
                <el-col :span="12">
                  <el-form-item label="学历层次">
                    <el-select v-model="form.educationalLevelId" filterable placeholder="请选择" class="input">
                      <el-option
                        v-for="item in dict.education"
                        :key="item.id"
                        :label="item.label"
                        :value="item.value"
                      />
                    </el-select>
                  </el-form-item>
                </el-col>
                <el-col :span="12">
                  <el-form-item label="入学年份">
                    <el-date-picker
                      v-model="form.enterDate"
                      placeholder="请选择"
                      type="year"
                      value-format="yyyy"
                      style="width: 250px;"
                      @change="loadColleges"
                    />
                  </el-form-item>
                </el-col>
              </el-row>
              <el-row :gutter="0.5">
                <el-col :span="12">
                  <el-form-item label="学院">
                    <el-select
                      v-model="form.academyDepartId"
                      filterable
                      placeholder="请选择"
                      class="input"
                      @change="loadMajors"
                    >
                      <el-option
                        v-for="item in colleges"
                        :key="item.id"
                        :label="item.name"
                        :value="item.id"
                      />
                    </el-select>
                  </el-form-item>
                </el-col>
                <el-col :span="12">
                  <el-form-item label="专业">
                    <el-select v-model="form.majorDepartId" filterable placeholder="请选择" class="input">
                      <el-option
                        v-for="item in majors"
                        :key="item.id"
                        :label="item.name"
                        :value="item.id"
                      />
                    </el-select>
                  </el-form-item>
                </el-col>
              </el-row>
            </el-tab-pane>

            <el-tab-pane label="工作经历" name="third">
              <el-row :gutter="0.5">
                <el-col :span="12">
                  <el-form-item label="从事行业">
                    <el-input v-model="form.industry" class="input" />
                  </el-form-item>
                </el-col>
                <el-col :span="12">
                  <el-form-item label="工作单位">
                    <el-input v-model="form.workUnit" class="input" />
                  </el-form-item>
                </el-col>
              </el-row>
              <el-row :gutter="0.5">
                <el-col :span="12">
                  <el-form-item label="职称">
                    <el-input v-model="form.postitional" class="input" />
                  </el-form-item>
                </el-col>
                <el-col :span="12">
                  <el-form-item label="职务">
                    <el-input v-model="form.job" class="input" />
                  </el-form-item>
                </el-col>
              </el-row>
            </el-tab-pane>

            <el-tab-pane label="个人简介" name="forth">
              <el-form-item>
                <SimpleEditor
                  v-model="brief"
                  :is-clear="isClear"
                  height="180px"
                  style="width: 760px;border: none;"
                  @change="wangEditorChange"
                />
              </el-form-item>
            </el-tab-pane>

            <el-tab-pane v-if="form.studentUser != null" label="支撑材料" name="five">
              <el-form-item>
                <el-upload
                  ref="upload"
                  accept="image/jpeg, image/gif, image/png, image/bmp"
                  list-type="picture-card"
                  :class="{hide:true}"
                  :auto-upload="false"
                  :on-preview="handlePictureCardPreview"
                  :file-list="fileList"
                  :action="imgFileUploadApi + '?name=' + form.name"
                />
                <el-dialog title="支撑材料" :append-to-body="true" :visible.sync="dialogVisible">
                  <img width="100%" :src="dialogImageUrl" alt="">
                </el-dialog>
              </el-form-item>
            </el-tab-pane>
          </el-tabs>

          <el-row>
            <el-form-item v-permission="permission.verify" label="认证状态">
              <el-select v-model="form.verifyStatus" filterable placeholder="请选择" style="width: 120px">
                <el-option
                  v-for="item in dict.verify_status"
                  :key="item.id"
                  :label="item.label"
                  :value="item.value"
                />
              </el-select>
            </el-form-item>
            <el-form-item label="状态">
              <el-radio v-for="item in dict.data_status" :key="item.id" v-model="form.isEnable" :label="item.value">{{ item.label }}</el-radio>
            </el-form-item>
          </el-row>

          <el-form align="right">
            <el-button type="text" @click="crud.cancelCU">取消</el-button>
            <el-button :loading="crud.cu === 2" type="primary" @click="crud.submitCU">确认</el-button>
          </el-form>
        </el-form>
      </el-dialog>

      <!--表格渲染-->
      <el-table ref="table" v-loading="crud.loading" :data="crud.data" size="small" style="width: 100%;" @selection-change="crud.selectionChangeHandler">
        <el-table-column type="selection" width="50px" />
        <el-table-column prop="name" label="姓名" width="80px" />
        <el-table-column prop="verifyStatus" label="认证状态" width="80px">
          <template slot-scope="scope">
            <div v-if="scope.row.verifyStatus=='0'">待认证</div>
            <div v-if="scope.row.verifyStatus=='1'" style="color: limegreen">认证通过</div>
            <div v-if="scope.row.verifyStatus=='2'" style="color: #FF4949">认证未通过</div>
          </template>
        </el-table-column>
        <el-table-column prop="gender" label="性别" width="50px">
          <template slot-scope="scope">
            {{ dict.label.gender_type[scope.row.gender] }}
          </template>
        </el-table-column>
        <!-- <el-table-column prop="birthDate" label="出生年月">
          <template slot-scope="scope">
            <span>{{ parseTime(scope.row.birthDate, '{y}-{m}') }}</span>
          </template>
        </el-table-column> -->
        <el-table-column prop="nationId" label="民族" width="100px">
          <template slot-scope="scope">
            {{ dict.label.nation[scope.row.nationId] }}
          </template>
        </el-table-column>
        <el-table-column prop="politicalId" label="政治面貌" width="100px">
          <template slot-scope="scope">
            {{ dict.label.political_climate[scope.row.politicalId] }}
          </template>
        </el-table-column>
        <el-table-column prop="phone" label="联系电话" width="120px" />
        <el-table-column prop="enterDate" label="入学年份" width="100px" />
        <el-table-column prop="educationalLevelId" label="学历层次" width="100px">
          <template slot-scope="scope">
            {{ dict.label.education[scope.row.educationalLevelId] }}
          </template>
        </el-table-column>
        <!-- <el-table-column prop="birthPlace" label="生源地" width="180px" />
        <el-table-column prop="address" label="当前地址" /> -->
        <el-table-column prop="academyDepartment.name" label="院系" width="180px" />
        <el-table-column prop="majorDepartment.name" label="专业" />
        <el-table-column prop="isEnable" label="状态" fixed="right" width="50">
          <template slot-scope="scope">
            <el-switch
              v-model="scope.row.isEnable"
              active-color="#409EFF"
              inactive-color="#F56C6C"
              @change="changeEnabled(scope.row, scope.row.isEnable)"
            />
          </template>
        </el-table-column>
        <el-table-column v-permission="['admin','student:edit','student:del']" label="操作" width="120px" align="center" fixed="right">
          <template slot-scope="scope">
            <udOperation
              :data="scope.row"
              :permission="permission"
            />
          </template>
        </el-table-column>
      </el-table>
      <!--分页组件-->
      <pagination />
    </div>
  </div>
</template>

<script>
import { mapGetters } from 'vuex'
import crudStudent from '@/api/anniversary/student'
import { getToken } from '@/utils/auth'
import CRUD, { presenter, header, form, crud } from '@crud/crud'
import rrOperation from '@crud/RR.operation'
import crudOperation from '@crud/CRUD.operation'
import udOperation from '@crud/UD.operation'
import pagination from '@crud/Pagination'
import { getColleges, getDepartments, getDepartmentYears } from '@/api/anniversary/department'
import SimpleEditor from '@/components/SimpleEditor/index'
import request from '../../../utils/request'
const defaultForm = { id: null, userId: null, name: null, gender: 2, birthDate: null, nationId: null, politicalId: null, enterDate: null, educationalLevelId: null, academyDepartId: null, facultyDepartId: null, majorDepartId: null, classDepartId: null, idCardNo: null, birthPlace: null, industry: null, workUnit: null, postitional: null, job: null, address: null, phone: null, qq: null, weixin: null, brief: null, verifyStatus: 0, createBy: null, createTime: null, updateBy: null, updateTime: null, sort: null, remark: null, isEnable: true }
export default {
  name: 'Student',
  components: { pagination, crudOperation, rrOperation, udOperation, SimpleEditor },
  mixins: [presenter(), header(), form(defaultForm), crud()],
  dicts: ['gender_type', 'verify_status', 'data_status', 'political_climate', 'nation', 'education'],
  cruds() {
    return CRUD({ title: '学生校友', url: 'api/student', sort: 'id,desc', crudMethod: { ...crudStudent }})
  },
  data() {
    return {
      headers: { 'Authorization': getToken() },
      // 编辑器内容
      brief: '',
      isClear: false,
      activeName: 'first',
      years: [],
      loading: false,
      queryColleges: [],
      queryMajors: [],
      colleges: [],
      majors: [],
      fileList: [], // upload多文件数组
      dialogImageUrl: '',
      dialogVisible: false,
      permission: {
        add: ['admin', 'student:add'],
        edit: ['admin', 'student:edit'],
        del: ['admin', 'student:del'],
        verify: ['admin', 'student:verify']
      },
      rules: {
        name: [
          { required: true, message: '名称不能为空', trigger: 'blur' }
        ]
      },
      queryTypeOptions: [
        { key: 'name', display_name: '名称' },
        { key: 'gender', display_name: '性别' },
        { key: 'nationId', display_name: '民族' },
        { key: 'politicalId', display_name: '政治面貌' },
        { key: 'educationalLevelId', display_name: '学历层次' },
        { key: 'academyDepartId', display_name: '学院' },
        { key: 'facultyDepartId', display_name: '系部' },
        { key: 'majorDepartId', display_name: '专业' },
        { key: 'classDepartId', display_name: '班级' },
        { key: 'verifyStatus', display_name: '认证状态' },
        { key: 'isEnable', display_name: '状态' }
      ]
    }
  },
  computed: {
    ...mapGetters(['baseApi', 'imgFileUploadApi', 'studentBatchImportApi'])
  },
  mounted() {
    this.brief = '' // 设置富文本框默认显示内容
  },
  methods: {
    // 钩子：在获取表格数据之前执行，false 则代表不获取数据
    [CRUD.HOOK.beforeRefresh]() {
      return true
    },
    [CRUD.HOOK.afterToCU](crud, form) {
      if (form.id != null && form.brief != null) { this.brief = form.brief } else { this.brief = '' }
      this.activeName = 'first'

      form.verifyStatus = `${form.verifyStatus}`
      form.isEnable = `${form.isEnable}`
      form.gender = `${form.gender}`
      form.inGzmu = `${form.inGzmu}`
      if (form.nationId != null) {
        form.nationId = `${form.nationId}`
      }
      if (form.politicalId != null) {
        form.politicalId = `${form.politicalId}`
      }
      if (form.educationalLevelId != null) {
        form.educationalLevelId = `${form.educationalLevelId}`
      }
      if (form.enterDate != null) {
        form.enterDate = `${form.enterDate}`
        // 加载学院信息
        this.colleges = [] // 先清空之前的学院信息
        getColleges({ college: '', year: form.enterDate }).then(res => {
          this.colleges = res
          // 加载专业信息
          this.majors = [] // 先清空之前的专业信息
          var params = { isEnable: true, parentId: form.academyDepartId }
          getDepartments(params).then(res => {
            this.majors = res.content
          })
        })
      }

      this.fileList = []
      if (form.studentUser != null && form.studentUser.certificatePhotoPath != null) {
        var arrayOfStrings = form.studentUser.certificatePhotoPath.split(';')
        for (var i = 0; i < arrayOfStrings.length; i++) {
          if (arrayOfStrings[i].trim() === '') continue

          var url = this.baseApi + '/upload/图片/' + arrayOfStrings[i]
          this.fileList.push({
            name: arrayOfStrings[i],
            url: url
          })
        }
      }
    },
    getEnterYears() {
      if (this.loading === false) {
        this.loading = true
        setTimeout(() => {
          getDepartmentYears({ college: '' }).then(res => {
            if (res != null) {
              this.years = res
            }
          }
          )
        }, 100)
      }
    },
    loadQueryColleges(e) {
      this.queryColleges = []
      this.query.academyDepartId = null
      this.query.majorDepartId = null
      getColleges({ college: '', year: e }).then(res => {
        this.queryColleges = res
      })
    },
    loadQueryMajors(e) {
      this.queryMajors = []
      var params = { isEnable: true, parentId: e }
      getDepartments(params).then(res => {
        this.queryMajors = res.content
      })
    },
    loadColleges(e) {
      this.colleges = []
      this.majors = []
      this.form.academyDepartId = null
      this.form.majorDepartId = null
      if (e != null) {
        getColleges({ college: '', year: e }).then(res => {
          this.colleges = res
        })
      }
    },
    loadMajors(e) {
      this.majors = []
      var params = { isEnable: true, parentId: e }
      getDepartments(params).then(res => {
        this.majors = res.content
      })
    },
    wangEditorChange(val) {
      console.log(val)
    },
    // 点击文件列表中已上传的文件时的钩子
    handlePictureCardPreview(file) {
      this.dialogImageUrl = file.url
      this.dialogVisible = true
    },
    // 身份证验证
    validID(rule, value, callback) {
      // 身份证号码为15位或者18位，15位时全为数字，18位前17位为数字，最后一位是校验位，可能为数字或字符X
      const reg = /(^\d{15}$)|(^\d{18}$)|(^\d{17}(\d|X|x)$)/
      if (reg.test(value)) {
        callback()
      } else {
        if (value.length === 0) {
          callback()
        }
        callback(new Error('身份证号码不正确'))
      }
    },
    changeEnabled: function(data, val) {
      this.$confirm('此操作将 "' + this.dict.label.data_status[val] + '" ' + data.name + ', 是否继续？', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        crudStudent.edit(data).then(res => {
          this.crud.notify(this.dict.label.data_status[val] + '成功', CRUD.NOTIFICATION_TYPE.SUCCESS)
        }).catch(() => {
          data.isEnable = !data.isEnable
        })
      }).catch(() => {
        data.isEnable = !data.isEnable
      })
    },
    /* 导入excel功能begin*/
    beforeUploadFile(file) {
      const extension = file.name.substring(file.name.lastIndexOf('.') + 1)
      const size = file.size / 1024 / 1024
      if (!((extension === 'xlsx') || (extension === 'xls'))) {
        this.$message.warning('只能上传后缀是xlsx或xls的文件')
        return false
      }
      if (size > 10) {
        this.$message.warning('文件大小不得超过10M')
        return false
      }
    },
    // 上传进度
    handleUploadProcess(event, file) {
      this.fileUploadPercent = Number(file.percentage.toFixed(0))
    },
    // 上传成功
    handleUploadSuccess(result, file) {
      if (result.success === 'ok') {
        // ok时为全部成功导入
        this.crud.notify('全部导入成功，批量导入' + result.sum + '条', CRUD.NOTIFICATION_TYPE.SUCCESS)
        this.fileUploadPercent = 0
      } else {
        var fileName = result.fileName
        var errorNum = result.errorNum
        console.log(result.fileName)
        this.$confirm('批量导入部分成功' + (result.sum - errorNum) + '条,失败' + errorNum + '条,是否下载错误数据', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).then(() => {
          request({
            url: `/api/localStorage/downloadFile`,
            params: {
              'pathAndName': fileName
            },
            method: 'get',
            responseType: 'blob'
          }).then(response => {
            const url = window.URL.createObjectURL(new Blob([response]))
            const link = document.createElement('a')
            link.style.display = 'none'
            link.href = url
            link.setAttribute('download', fileName)
            document.body.appendChild(link)
            link.click()
            document.body.removeChild(link)
          })
        }).catch(() => {
          this.$message({
            type: 'info',
            message: '取消下载'
          })
        })
        this.crud.notify('部分导入成功,请检查后重试', CRUD.NOTIFICATION_TYPE.SUCCESS)
        this.fileUploadPercent = 0
      }
    },
    // 上传失败
    handleUploadError(e, file, fileList) {
      // this.$message.error('服务器发生错误！上传失败, 请重试!');
      this.fileUploadPercent = 0
      const msg = JSON.parse(e.message)
      this.$notify({
        title: msg.message,
        type: 'error',
        duration: 2500
      })
    },
    handleRemove(file, fileList) {
      this.$emit('on-remove', fileList)
      this.fileList = fileList
    },
    handleExceed(files, fileList) {
      this.$message.warning(`仅可上传${this.limit}个附件`)
    }
    /* 导入excel功能end*/
  }
}
</script>

<style scoped>

</style>

<style>
	.input {
    width: 250px;
	}

  .hide .el-upload--picture-card {
    display: none;
  }

  .hide .el-icon-delete{
    display: none;
  }
</style>
